import React, { memo, useCallback, useContext, useEffect } from 'react'
import song from 'apis/song'
import useAsyncFn from 'hooks/useAsyncFn'
import { LoginContext } from 'reducers/log'
import Header from './Header'
import { ACTIONS, PlayMusicContext } from 'reducers/playMusic'
import styles from './style.module.css'
import { Spinner } from '@blueprintjs/core'
import MusicList from 'components/MusicList'
const RecommendDaily = memo(() => {
  const [_, playDispatch] = useContext(PlayMusicContext)
  const [logState] = useContext(LoginContext)
  const [state, getRecommendSongsFn] = useAsyncFn(song.getRecommendSongs)
  const { isLogined } = logState
  const { value, loading } = state
  useEffect(() => {
    if (isLogined) {
      getRecommendSongsFn()
    }
  }, [isLogined])
  const playAll = useCallback((autoPlay?: boolean) => {
    playDispatch({
      type: ACTIONS.SET_PLAY_LIST,
      payload: {
        playList: value,
      },
    })
    if (autoPlay) {
      const item = value?.[0]
      playDispatch({
        type: ACTIONS.PLAY,
        payload: {
          musicId: item?.id,
          music: {
            ...item,
            picUrl: item?.album.blurPicUrl,
            duration: item!.duration / 1000,
          },
        },
      })
    }
  }, [])
  return (
    <div className={styles.root}>
      <Header>
        {isLogined && (
          <div className='playAll' onClick={() => playAll(true)}>
            播放全部
          </div>
        )}
      </Header>
      {isLogined ? (
        <div className='content'>
          {loading ? <Spinner /> : <MusicList data={value || []} onPlayAll={() => playAll()} />}
        </div>
      ) : (
        <div className={styles.needLogin}>请先登陆哦</div>
      )}
    </div>
  )
})
export default RecommendDaily
